<template>
  <div class="app-container">
    <el-tabs v-model="editableTabsValue" type="border-card" style="padding: 30px 0;">
      <el-tab-pane
        label="欠款列表"
        name="欠款列表"
      >
        <br>
        <el-table
          v-loading="listLoading"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
        > 
          <el-table-column align="center" label="序号" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="会员编号" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.patientCode }}
            </template>
          </el-table-column>
          <el-table-column label="姓名" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.patientName }}
            </template>
          </el-table-column>
          <el-table-column label="欠款金额" width="80" align="center">
            <template slot-scope="scope">
              {{ scope.row.totalDebtAmount }}
            </template>
          </el-table-column>
          <el-table-column label="欠款时间" width="140" align="center">
            <template slot-scope="scope">
              {{ scope.row.createdTime }}
            </template>
          </el-table-column>
          <el-table-column label="已还金额" width="80" align="center">
            <template slot-scope="scope">
              {{ scope.row.returnedAmount }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="80" align="center">
            <template slot-scope="scope">
              {{ scope.row.status | statusFilter }}
            </template>
          </el-table-column>
          <el-table-column label="还款日期" width="140" align="center">
            <template slot-scope="scope">
              {{ scope.row.status == 1 ? scope.row.updatedTime : "--" }}
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="操作" align="center" width="400" >
            <template slot-scope="scope">
              <el-button type="primary" @click="optionReturn(scope.row)">还款操作</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          layout="->, total, prev, pager, next"
          :total="this.total"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="clickCurPage"
          >
        </el-pagination>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="还款详情" :visible.sync="formVisible" >
      <el-divider content-position="left"><b>{{ form.patientCode + ' ' + form.patientName }}</b></el-divider>
      <el-form ref="form" :model="form" label-width="120px" :rules="rules">
        <el-form-item label="欠款金额 (元)" prop="totalDebtAmount">
          <el-input v-model="form.totalDebtAmount" :disabled="true"/>
        </el-form-item>
        <el-form-item label="已还金额 (元)" prop="returnedAmount">
          <el-input v-model="form.returnedAmount" :disabled="true"/>
        </el-form-item>
        <el-form-item label="还款 (元)" prop="returnAmount">
          <el-input v-model="form.returnAmount" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmReturnPaid">确 定</el-button>
          <el-button @click="cancelInfo">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<script>

import { getList, returnPaid } from '@/api/returnPaid'
import { getList as getPatientList} from '@/api/patient'
import { GuidanceStatusEnum } from '@/enums/guidanceStatusEnum.js'
import { CardEnum } from '@/enums/CardEnum.js'
import { getList as getCardList } from '@/api/card'
import { getList as getMyCardList, add as addUserCard, getAllStoredCardList } from '@/api/patientCard'
import { getVisitAmount, add as addPaid } from '@/api/paid'
import { dateToString, addDate } from '../../utils/dateUtil'
import Decimal from 'decimal.js';

export default {
  name: "Paid",
  filters: {
    statusFilter(status) {
      const statusMap = ['未还款', '已还款']
      return statusMap[status]
    },
  },
  data() {
    const validateReturnAmount = (rule, value, callback) => {
      if (!value || value <= 0) callback(new Error('请输入还款金额')) 
      else callback()
    }
    return {
      list: null,
      listLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      info: {},
      form: {},
      dialogTitle: '添加来源',
      depts:[],
      rules: {
        returnAmount: [{ required: true, trigger: 'blur', validator: validateReturnAmount }],
      },
      editableTabsValue: '欠款列表',
      editableTabs: [],
      defaultOpen: ['会员管理', '诊中处置', '会员就诊记录查询', '缴费/卡/券', '租借药盒'],
      patientCardEnum: [],
      dialogPayableInfo: {}
    }
  },
  created() {
    this.fetchData()
    this.startInterval()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      this.initListData()
    },
    initListData() {
      var loginInfo = this.$store.getters.userInfo.loginInfo
      var deptId = loginInfo.loginDept.deptId
      var jobOfficeId = loginInfo.loginJobOffice?loginInfo.loginJobOffice.jobOfficeId:undefined
      this.$set(this, 'listLoading', true)
      getList({currentPage: this.currentPage, pageSize: this.pageSize, deptId: deptId}).then(res=>{
        console.log(res.data)
        this.list = res.data.records
        this.$set(this, 'total', res.data.total)
        this.noMasterDoctorNum = this.list.filter(item=> !item.doctorId).length
        this.doneWaitingNum = this.list.filter(item=> item.remainderTime == 0).length
        this.noInspectionNum = this.list.filter(item=> !item.masterDoctor).length
        this.noCheckNum = this.list.filter(item=> !item.masterDoctor).length
        this.noInfoNum = this.list.filter(item=> !item.masterDoctor).length
        this.listLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.listLoading = false
      })
    },
    startInterval() {
      this.intervalId = setInterval(this.callApi, 1000 * 60);
    },
    stopInterval() {
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }
    },
    callApi() {
      // 调用接口的逻辑
      console.log('刷新欠款列表');
      this.initListData()
    },
    clickCurPage(val){
      this.currentPage = val
      this.initListData()
    },
    optionReturn(row) {
      this.form = row
      this.formVisible = true
    },
    cancel() {
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    async confirmReturnPaid() {
      // 确认还款
      this.$refs.form.validate(async valid => {
        if (valid) {
          console.log('form', this.form)
          let returnPaidRes = await returnPaid(this.form)
          console.log('确定还款', returnPaidRes)
          this.formVisible = false
          this.initListData()
          this.$message({
            type: 'success',
            message: '还款成功!'
          });
        } else {
          console.log('error submit!!')
          return false
        }
      })
      
    },
    checkNumInput(obj, prop, content) {
      // 判空
      if(!content) this.$set(obj, prop, 0)
      // 删除0开头
      this.$set(obj, prop, Number(content))
      // 负数时改为0
      if(!content) this.$set(obj, prop, 0)
    },
    cancelInfo() {
      this.formVisible = false
    }
  },
}
</script>

<style lang="scss" scoped>
  .del-btn {
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 4px;
  }
  .activity-box {
    display: flex;
    justify-content: space-around;
  }

  .first-row {
    position: absolute;
    top: 8px;
    left: 3px;
    width: 93%;
  }
  
  .second-row {
    position: absolute;
    top: 38px;
    left: 3px;
    width: 93%;
  }
  table {
      border-collapse: collapse;
      margin: 20px 0;
      font-family: Arial, sans-serif;
  }
  th, td {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: center;
  }
  th {
      background-color: #f2f2f2;
      font-weight: bold;
  }

  
  .repair-box ::v-deep .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 93%;
    margin: 0 0
  }

  ::v-deep .el-tabs__item {
    height: 30px;
    line-height: 30px;
  }
  .app-container > ::v-deep .el-tabs--border-card > .el-tabs__header{
    position: fixed;
    z-index: 98;
    top: 84px;
  }

  .el-main > .patient-base-info > .el-collapse {
    position: fixed;
    z-index: 98;
    top: 160px;
    width: 72%
  }
  .el-main > ::v-deep .el-tabs--border-card {
    margin-top: 70px;
  }
  .patient-base-info {
    position: fixed;
    z-index: 97;
    background-color: #fff;
    width: 72%;
    padding: 0 16px;
  }
  .table-separate {
    opacity: 0;border: none
    th {
      opacity: 0;border: none
    }
  }

  .drug-payment-cell-1 {
    width: 90px;
  }
  .drug-payment-cell-2 {
    width: 200px;
  }
  .drug-payment-cell-3 {
    width: 140px;
  }
  .drug-payment-cell-4 {
    width: 250px;
  }
  .drug-payment-cell-5 {
    width: 120px;
  }
  .drug-payment-cell-6 {
    width: 200px;
  }
  .card-payment-description {
    font-size: 12px;
    min-height: 18px;
    line-height: 18px;
    padding: 5;
    text-align: left;
  }

</style>